import { consts } from "@/module-00-codebase/pkg-00-const";
import { asyncOne, isWeb } from "@/module-00-codebase/pkg-02-tool";

export class I18n {
  public async translate(template: string, ...args: any[]) {
    try {
      return parseTemplate(cache[template] || (await asyncOne(async () => (cache[template] = await transTemplate(template)), template)), args);
    } catch (e) {
      return parseTemplate(template, args);
    }
  }
}
export const initializing = async () => {
  if (isWeb()) {
    transTemplate = async (content: string) => content;
  } else {
    const plugin: any = requirePlugin("wx069ba97219f66d99");
    const defaultOptions = { lfrom: "en_US", lto: "zh_CN" };
    transTemplate = async (content: string) => (await new Promise((r, j) => plugin.translate({ ...defaultOptions, content, success: (res: any) => r(res.result), fail: () => j(new Error()) }))) as string;
  }
};
const REGEXP = () => new RegExp(consts.PAD, "g");
const cache = Object.create(null);
const parseTemplate = (content: string, args: any[]) => content.split(REGEXP()).reduce((pre, s, i) => `${pre}${s}${args[i] || ""}`, "");
let transTemplate: any;
